using System;
using System.Collections.Concurrent;
using System.ServiceModel;
using DemoLib.Data.Repositories;
using DemoLib.Shared.Contracts;
using DemoLib.Shared.Models;

namespace DemoLib.Service.Services
{
    [ServiceBehavior(InstanceContextMode =  InstanceContextMode.PerCall, ConcurrencyMode = ConcurrencyMode.Multiple )]
    public class AuthoService : IAuthoService
    {
        private static readonly ConcurrentDictionary<string, User> UserTokens = new ConcurrentDictionary<string, User>();

        #region Implementation of IAuthoService

        public AuthContract<string> AuthoriseUser(AuthContract<LogOnModel> logon)
        {
            var userRepository = new UserRepository();
            
            var user = userRepository.VarifyUser(logon.Data.UserName, logon.Data.Password);
            
            if(user != null)
            {
                var newToken = Guid.NewGuid().ToString();
                UserTokens.TryAdd(newToken, user);
                return new AuthContract<string>()
                    {
                        Data = newToken
                    };
            }

            throw new FaultException("Invalid username or password.");
        }

        //[OperationBehavior(ReleaseInstanceMode = ReleaseInstanceMode.AfterCall)]
        public void Logout(AuthContract<string> userToken)
        {
            if(UserTokens.ContainsKey(userToken.Key))
            {
                User user;
                if(!UserTokens.TryRemove(userToken.Key, out  user))
                {
                    throw  new FaultException("Invalid operation");
                }
            }

            throw new FaultException("Invalid operation");
        }

        #endregion
    }
}